package com.king.photo.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.king.photo.util.Bimp;
import com.king.photo.util.HttpRequest;
import com.king.photo.util.ImageItem;
import com.shouxun.microclassroom.R;

public class SelectPicPopupWindow2 extends Activity implements OnClickListener{  
	  
    private Button btn_take_photo,btn_pick_photo, btn_cancel;  
    private LinearLayout layout;  
    String path;
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.item_popupwindows);  
        btn_take_photo = (Button) this.findViewById(R.id.item_popupwindows_camera);  
        btn_pick_photo = (Button) this.findViewById(R.id.item_popupwindows_Photo);  
        btn_cancel = (Button) this.findViewById(R.id.item_popupwindows_cancel);  
          
        layout=(LinearLayout)findViewById(R.id.ll_popup);  
          
        //添加选择窗口范围监听可以优先获取触点，即不再执行onTouchEvent()函数，点击其他地方时执行onTouchEvent()函数销毁Activity  
        layout.setOnClickListener(new OnClickListener() {  
              
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                Toast.makeText(getApplicationContext(), "提示：点击窗口外部关闭窗口！",   
                        Toast.LENGTH_SHORT).show();   
            }  
        });  
        //添加按钮监听  
        btn_take_photo.setOnClickListener(this); 
        btn_cancel.setOnClickListener(this);  
        btn_pick_photo.setOnClickListener(this);  
        WindowManager m = getWindowManager();    
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高    
        android.view.WindowManager.LayoutParams p = getWindow().getAttributes();  //获取对话框当前的参数值    
        p.height = (int) (d.getHeight() * 0.3);   //高度设置为屏幕的1.0   
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.8   
        p.alpha = 1.0f;      //设置本身透明度  
        p.dimAmount =0.0f;      //设置黑暗度  
        p.gravity=Gravity.BOTTOM;
        
        getWindow().setAttributes(p);   
    }  
      
    //实现onTouchEvent触屏函数但点击屏幕时销毁本Activity  
    @Override  
    public boolean onTouchEvent(MotionEvent event){  
        finish();  
        return true;  
    }  
  
    public void onClick(View v) {  
        switch (v.getId()) { 
        case R.id.item_popupwindows_camera:  
        	photo();
            break;  
        case R.id.item_popupwindows_Photo:     
        	Intent intent = new Intent(SelectPicPopupWindow2.this,
					Album2Activity.class);
			startActivity(intent);
			finish();
            break;  
        case R.id.item_popupwindows_cancel: 
        	 finish();  
            break;  
        default:  
            break;  
        }  
       
    }  
    private static final int TAKE_PICTURE = 0x000001;
	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
				TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
				String szImei = TelephonyMgr.getDeviceId(); 
				
				String fileName = String.valueOf("Thumb"
						+szImei+ System.currentTimeMillis());
				String fileName1 = String.valueOf(szImei+System
						.currentTimeMillis());
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				ImageItem takePhoto = new ImageItem();
				takePhoto.setBitmap(bm);
				File f = new File("/sdcard/Photo_LJ/", fileName
						+ ".png");
				File f1 = new File("/sdcard/Photo_LJ/", fileName1
						+ ".png");
				FileOutputStream out, out1;
				try {
					out = new FileOutputStream(f);
					out1 = new FileOutputStream(f1);
					bm.compress(Bitmap.CompressFormat.PNG, 50, out);
					bm.compress(Bitmap.CompressFormat.PNG, 100, out1);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				takePhoto.setImagePath(f1.getPath());
				takePhoto.setThumbnailPath(f.getPath());
			
				Bimp.tempSelectBitmap.add(takePhoto);
				
					
						
			
			}
			new Thread() {
				public void run() {
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
						ImageItem item = Bimp.tempSelectBitmap.get(i);
						String urlPath = "http://www.17smile.cn/app/uploadimagefile";
						HttpRequest request = HttpRequest.post(urlPath);
						request.part("fileType", "vote");
						request.part("flag", "image");
						request.part("imageName",item.getThumbnailPath().split("Thumb")[1]);
						request.part("uploadimage",
								new File(item.getImagePath()));
						String path=request.body();
						
							sb.append(path+","+item.getImagePath()+",")	; 
						
					}
					final String s = sb.substring(0, sb.length() - 1);
					System.out.println(s.toString());
					Message msg=new Message();
					msg.obj=s;
					handler.sendMessage(msg);
				}
			}.start();
			break;
		}
	}
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			path=msg.obj.toString();
			Toast.makeText(getApplicationContext(), path,3000).show();
			finish();
		}
	};
}  
